<?php
	include 'header.php';
	if ( isset( $_POST['pollname'] ) && isset( $_POST['description'] ) && !empty( $_POST['pollname'] ) && !empty( $_POST['description'] ) ) {
		$pollname = $_POST['pollname'];
		$pollname = htmlspecialchars(addslashes($pollname));
		//check if pollname exists
		$res = mysql_query(
			'SELECT
				pollname
			FROM
				polls
			WHERE
				pollname = "' . $pollname . '";'
		);

		if ( mysql_num_rows($res) == 0 ) {
			$userid = $_SESSION['userid'];
			$description = $_POST['description'];
			$description = htmlspecialchars(addslashes($description));
			$datetime = date("Y/m/d-H/i/s");
			mysql_query(
			'INSERT INTO
				polls
			SET
				pollname = "' . $pollname . '",
				userid = "' . $userid . '",
				created = "' . $datetime . '",
				description = "' . $description . '";'
				
			);
			$pollid = mysql_insert_id();
			$selector = $_POST['selector'];
			$i = 1 ;
			// Check if every choice is ok and insert it into polls
			while ( isset( $_POST["$i"] ) && !empty( $_POST["$i"] ) && $i<=$selector){
				$temp = $_POST["$i"];
				$temp = htmlspecialchars(addslashes($temp));
				mysql_query(
				'INSERT INTO
					pollchoices
				SET
					pollid = "' . $pollid . '",
					num_choice = "' . $i . '",
					choice = "' . $temp . '";'
				);
				$i++ ;
			}
			if ( $i<=$selector ){
				mysql_query(
					'DELETE FROM
						polls
					WHERE
						pollname = "' . $pollname . '";'
				);
				echo "<script> window.location = \"./create.php?missing=yes\"</script>";
			}
			else{
				echo "<script> window.location = \"./create_success.php\"</script>";
			}
		}
		else{
			echo "<script> window.location = \"./create.php?exists=yes\"</script>";
		}
	}
	else {
		echo "<script> window.location = \"./create.php?missing=yes\"</script>";
	}
	include "footer.php";
?>
